package cn.jdk.aqstool;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 *
 * semaphore 信号量
 *
 * 可以用此限流
 *
 * @author summit
 * @since 2021/8/8 15:56
 */
@Slf4j
public class SemaphoreTest {

	// 3 代表初始化 state=3  最大并行度为3	总的容量池
	static Semaphore semaphore = new Semaphore(3);

	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			Thread thread = new Thread(new Task(semaphore), "test-" + i);
			thread.start();
		}
	}


	static class Task implements Runnable {
		private final Semaphore semaphore;

		public Task(Semaphore semaphore) {
			this.semaphore = semaphore;
		}

		@Override
		public void run() {
			// 获取资源
			try {
				if (semaphore.tryAcquire(1, 1, TimeUnit.SECONDS)) {
					//获取公共资源 state-1
					//semaphore.acquire(1);
					log.error("当前线程：{},获取锁成功", Thread.currentThread().getName());
					TimeUnit.SECONDS.sleep(3);

					// 释放公共资源 state+1
					semaphore.release(1);
				} else {
					log.warn("获取失败，不等了");
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}


